<template>
  <LeakageAnalysis :meterList="meterList"></LeakageAnalysis>
  <div class="layout-wrapper">
    <!-- 左侧内容区域 -->
    <div class="left-content">
      <!-- 表计列表 -->
      <div class="meter-list" v-loading="loading">
        <el-card shadow="never" body-style="height: 90%;width: 100%;display: flex;flex-direction: column"
          style="height: 100%; overflow: auto">
          <template #header>
            <div>静态数据分析
              <el-tag type="info" size="small" style="margin-left: 8px;">
                共选择 {{ dayjs(dateRange[1]).diff(dayjs(dateRange[0]), 'day') }} 天
              </el-tag>
            </div>
            <div>
              <el-checkbox v-model="showOnlyLeakageMeter">仅查看存在漏损表计</el-checkbox>
            </div>
          </template>
          <div class="filter-section">
            <FilterHeader width="16rem" :is-range="true" :max-days="31" v-model="dateRange"></FilterHeader>
            <!-- 表计编号搜索框 -->
            <el-input v-model="meterCodeSearch" placeholder="搜索表计编号" style="width: 12rem" clearable
              prefix-icon="search"></el-input>
            <el-select filterable style="width: 10rem" clearable v-model="areaId" placeholder="区域筛选">
              <el-option v-for="item in areaStore.areas" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </div>
          <div style="flex: 1">
            <StaticDataAnalysis :selectedMeterId="+selectedMeter?.id" @toggle-view="toggleView"
              :meterList="filterdMeterList" @row-click="handleMeterClick">
            </StaticDataAnalysis>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 右侧动态分析 - 仅在桌面端显示 -->
    <div class="right-content" v-if="!isMobileOrTablet">
      <el-card body-style="height: 100%; width: 100%;" style="height: 100%; display: flex; flex-direction: column">
        <template #header>
          <div class="card-header">
            动态数据分析
            <div>当前：{{ selectedMeter?.meter_code || "请选择表计" }}</div>
            <el-checkbox v-permission="'control_device'" v-if="selectedMeter?.type === 1" v-model="isDrainConsidered"
              @change="handleDrainConsideredChange">
              该表不计入漏损
            </el-checkbox>
          </div>
          <div class="header-actions" v-if="selectedMeter">
            <div class="view-toggle">
              <el-tooltip :content="currentView === 'chart' ? '切换为表格视图' : '切换为图表视图'
                " placement="top">
                <!-- 修复 underline 警告：使用字符串而非布尔值 -->
                <el-link underline="never" @click="toggleView">
                  <i class="fa" style="font-size: 1.2rem" :class="currentView === 'chart' ? 'fa-table' : 'fa-line-chart'
                    "></i>
                </el-link>
              </el-tooltip>
            </div>
          </div>
        </template>
        <div class="chart-container">
          <!-- 空状态展示 -->
          <el-empty style="height: 100%; width: 100%" v-if="!selectedMeter" description="请在左侧选择表计以查看动态分析数据"
            :imgae-size="200">
            <template #image> </template>
          </el-empty>
          <!-- 数据展示组件 -->
          <component v-else :is="currentComponent" :id="selectedMeter.id" :dateRange="dateRange">
          </component>
        </div>
      </el-card>
    </div>
  </div>

  <!-- 移动端/平板端动态分析对话框 -->
  <el-dialog v-model="showMobileDialog" :title="`动态数据分析 - ${selectedMeter?.meter_code || ''}`" width="95%"
    :close-on-click-modal="false" :close-on-press-escape="true" class="mobile-dialog" :show-close="true"
    :append-to-body="true" :destroy-on-close="false">
    <template #header="{ close, titleId, titleClass }">
      <div class="dialog-header">
        <div class="dialog-title" :id="titleId" :class="titleClass">
          动态数据分析
          <div class="meter-info">当前：{{ selectedMeter?.meter_code || "请选择表计" }}</div>
        </div>
        <div class="dialog-actions">
          <el-checkbox v-permission="'control_device'" v-if="selectedMeter?.type === 1" v-model="isDrainConsidered"
            @change="handleDrainConsideredChange" size="small">
            该表不计入漏损
          </el-checkbox>
          <div class="view-toggle" v-if="selectedMeter">
            <el-tooltip :content="currentView === 'chart' ? '切换为表格视图' : '切换为图表视图'" placement="top">
              <el-button :icon="currentView === 'chart' ? 'Document' : 'TrendCharts'" size="small" @click="toggleView"
                circle />
            </el-tooltip>
          </div>
        </div>
      </div>
    </template>

    <div class="mobile-chart-container" v-if="showMobileDialog">
      <component v-if="selectedMeter" :is="currentComponent" :id="selectedMeter.id" :dateRange="dateRange"
        :key="selectedMeter.id">
      </component>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watchEffect, shallowRef, onMounted, computed, provide, onUnmounted, nextTick } from "vue";
import { handleError } from "@/utils/handleError";
import FilterHeader from "@/components/header/CustomDatePicker.vue";
import { useCompanyStore } from "@/stores/company";
import { updateMeterApi } from "@/api/meter";
import { getWaterStaticApi } from "@/api/waterLeakage";
import StaticDataAnalysis from "./components/StaticDataAnalysis.vue";
import dayjs from "dayjs";
import { getAsyncComponent } from "@/utils/asyncComponentLoader";
import { useRoute } from "vue-router";
import { useAreaStore } from '@/stores/area';
import { useMeterStore } from "@/stores/meter";
import LeakageAnalysis from "./components/LeakageAnalysis.vue";
import { useMobileDetection } from "@/composables/useMobileDetection";
let route = useRoute();
let areaStore = useAreaStore()
const companyStore = useCompanyStore();
const { isPC } = useMobileDetection();
// 设备检测
const isMobileOrTablet = computed(() => {
  return !isPC.value;
})
const showMobileDialog = ref(false);

// 监听窗口大小变化
const handleResize = () => {
  checkDevice();
  // 如果从移动端切换到桌面端，关闭对话框
  if (!isMobileOrTablet.value && showMobileDialog.value) {
    showMobileDialog.value = false;
  }
};

onMounted(() => {
  // 确保DOM渲染完成后再检测
  nextTick(() => {
    checkDevice();
  });
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});

// 统一的漏水判断函数
const isLeakedMeter = (meterItem) => {
  // 如果表计设置为不计入漏损统计，则不算作漏水
  if (meterItem.is_drain_considerd === false) {
    return false;
  }
  // 否则根据流量值判断（大于0表示漏水）
  return +meterItem.value > 0;
};

// 提供给子组件使用
provide('isLeakedMeter', isLeakedMeter);

// 切换视图
const currentView = ref("chart");
const toggleView = (str) => {
  if (typeof str === "string") {
    currentView.value = str;
  } else {
    currentView.value = currentView.value === "chart" ? "table" : "chart";
  }
  currentComponent.value =
    currentView.value === "chart" ? DynamicDataAnalysis : DynamicDataTable;
};

let DynamicDataAnalysis = getAsyncComponent(() =>
  import("./components/DynamicDataAnalysis.vue")
);
let DynamicDataTable = getAsyncComponent(() =>
  import("./components/DynamicDataTable.vue")
);

let meterStore = useMeterStore();
const currentComponent = shallowRef(DynamicDataAnalysis);

// 日期范围前3天
const defaultDateRange = [
  dayjs().subtract(1, "day").startOf("day").valueOf(),
  dayjs().startOf("day").valueOf(),
];

const dateRange = ref(defaultDateRange);

// 选中的表计ID
const selectedMeter = ref(null);
const isDrainConsidered = ref(true);

// 处理漏损统计变更
const handleDrainConsideredChange = async (value) => {
  if (!selectedMeter.value) return;
  try {
    await updateMeterApi({
      id: selectedMeter.value.id,
      is_drain_considerd: !value // 注意这里取反，因为复选框的含义是"不计入漏损"
    });
    ElMessage.success('更新成功');
    await meterStore.fetchMeterList({
      company_id: companyStore.currentCompany.id,
      type: 1,
    })
    fetchMeterData(dateRange.value?.[0], dateRange.value?.[1]);
  } catch (error) {
    handleError(error, '更新失败', true);
    isDrainConsidered.value = !value;
  }
};

// 处理表计点击
const handleMeterClick = async (row) => {
  selectedMeter.value = row;
  // 更新复选框状态
  isDrainConsidered.value = !row.is_drain_considerd;

  console.log('Meter clicked:', {
    isMobileOrTablet: isMobileOrTablet.value,
    selectedMeter: row
  });

  // 如果是移动端或平板端，显示对话框
  if (isMobileOrTablet.value) {
    // 使用nextTick确保状态更新完成
    await nextTick();
    showMobileDialog.value = true;

  }
};

onMounted(() => {
  let query = route.query;
  if (query.id) {
    // 先设置初始ID
    selectedMeter.value = { id: +query.id };

    // 加载表计详细信息
    watchEffect(() => {
      // 当meterList有数据且已设置ID时查找完整信息
      if (meterList.value.length > 0 && selectedMeter.value?.id) {
        const foundMeter = meterList.value.find(item => item.id === +selectedMeter.value.id);
        if (foundMeter) {
          selectedMeter.value = foundMeter;
          // 更新复选框状态
          isDrainConsidered.value = !foundMeter.is_drain_considerd;
        }
      }
    });
  }
});

let meterList = ref([]);
let loading = ref(false);
// 获取表计数据
const fetchMeterData = async (startDate, endDate) => {
  loading.value = true;
  try {
    let res = await getWaterStaticApi({
      id: companyStore.currentCompany.id,
      start_time: startDate,
      end_time: endDate,
    });
    meterList.value = res.data.map((item) => {
      let meterInfo = meterStore.meterList.find((meter) => meter.id === item.id)

      return {
        ...item,
        ...meterInfo,
      }
    })
  } catch (error) {
    handleError(error, "静态统计失败");
  } finally {
    loading.value = false;
  }
};

// 区域筛选
let areaId = ref(null);
let showOnlyLeakageMeter = ref(false);
// 表计编号搜索
let meterCodeSearch = ref("");

// 修改后的过滤逻辑
let filterdMeterList = computed(() => {
  if (!meterList.value) return [];
  let localList = [...meterList.value]

  // 表计编号搜索过滤
  if (meterCodeSearch.value) {
    localList = localList.filter((item) =>
      item.meter_code && item.meter_code.toLowerCase().includes(meterCodeSearch.value.toLowerCase())
    );
  }

  // 漏损表计过滤 - 使用统一的漏水判断函数
  if (showOnlyLeakageMeter.value) {
    localList = localList.filter((item) => isLeakedMeter(item));
  }


  // 区域过滤
  if (areaId.value) {
    localList = localList.filter((item) => item.area_id === areaId.value);
  }

  return localList;
});

// 当前公司ID
watchEffect(() => {
  if (companyStore.currentCompany.id) {
    fetchMeterData(dateRange.value?.[0], dateRange.value?.[1]);
    meterStore.fetchMeterList({
      company_id: companyStore.currentCompany.id,
      type: 1,
    })
  }
});

// 监听对话框状态变化（调试用）
watchEffect(() => {

});
</script>

<style scoped>
.layout-wrapper {
  display: flex;
  width: 100%;
  height: 100%;
  align-items: stretch;
  gap: 16px;
  position: relative;
}

.left-content {
  display: flex;
  flex-direction: column;
  width: 48%;
  height: 100%;
}

.right-content {
  width: 52%;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
}

.chart-container {
  flex: 1;
  width: 100%;
  height: 100%;
  overflow: auto;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  margin-bottom: 1rem;
  flex-shrink: 0;
}

.meter-list {
  flex-grow: 1;
  height: 0;
  height: 100%;
  min-height: 600px;
}

.card-header {
  display: flex;
  gap: 16px;
  align-items: center;
}

/* 移动端对话框样式 */
.mobile-dialog {
  --el-dialog-margin-top: 2vh;
}

/* 确保对话框在移动端正确显示 */
:deep(.mobile-dialog .el-dialog) {
  margin: 2vh auto !important;
  max-height: 96vh;
  display: flex !important;
  flex-direction: column;
}

:deep(.mobile-dialog .el-dialog__body) {
  flex: 1;
  padding: 10px 20px;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
  padding: 0;
}

.dialog-title {
  font-size: 16px;
  font-weight: 600;
  flex: 1;
}

.meter-info {
  font-size: 12px;
  color: #666;
  font-weight: normal;
  margin-top: 4px;
}

.dialog-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.mobile-chart-container {
  height: 70vh;
  width: 100%;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

/* 平板端和移动端的左侧内容调整 */
@media screen and (max-width: 1400px) {
  .layout-wrapper {
    flex-direction: column;
  }

  .left-content {
    width: 100%;
    height: 100%;
  }

  .right-content {
    display: none;
  }

  .filter-section {
    flex-wrap: wrap;
    gap: 8px;
  }

  .filter-section>* {
    min-width: 120px;
  }
}

/* 强制移动端对话框显示 */
@media screen and (max-width: 1024px) {
  :deep(.el-dialog__wrapper) {
    z-index: 2001 !important;
  }

  :deep(.mobile-dialog) {
    z-index: 2001 !important;
  }
}
</style>